<?php

class frmAddAccounts {
	/**
	 * Armazena o objeto principal
	 * 
	 * @access protected
	 * @name $mainObject
	 * @var Resource
	 */
	protected $mainObject = NULL;
	
	/**
	 * Armazena os widgets necessarios
	 * 
	 * @access private
	 * @name $widgets
	 * @var array
	 */
	public $widgets = array();
	
	/**
	 * Armazena a conta editada
	 * 
	 * @access private
	 * @name $__idaccount
	 * @var integer
	 */
	public $__idaccount = 0;
	
	/**
	 * Construtor
	 * 
	 * @name __construct
	 */
	public function __construct($main) {
		// Armazena o objeto principal
		$this->mainObject = $main;
		
		// Cria a janela
		$this->widgets['frmAddAccounts'] = new GtkWindow();
		$this->widgets['frmAddAccounts']->set_size_request(526, 265);
		$this->widgets['frmAddAccounts']->set_title("Configurações de contas");
        $this->widgets['frmAddAccounts']->set_position(Gtk::WIN_POS_CENTER);
        $box = new GtkHBox();
        $this->widgets['frmAddAccounts']->add($box);
        
        // Cria o treeview
        $model = new GtkListStore(GObject::TYPE_STRING, GObject::TYPE_STRING);
        $this->widgets['trvAccounts'] = Fabula::GtkTreeview($model);
        $this->widgets['trvAccounts']->connect("button-press-event", array($this, "trvAccounts_buttonPress"));
        $this->widgets['trvAccounts']->set_size_request(200, FALSE);
        $box->pack_start(Fabula::GtkViewPort($this->widgets['trvAccounts']), FALSE, FALSE);
        
        // Adiciona as colunas
		$a = $this->widgets['trvAccounts']->add_column(new GtkCellRendererText(), "#", "text");
		$a->set_visible(FALSE);
		$this->widgets['trvAccounts']->add_column(new GtkCellRendererText(), "Emails", "text");
		
		// Cria o formulario dos dados do email
		$fixed = new GtkFixed();
		$box->pack_start($fixed, TRUE, TRUE);
		
		// Cria o campo descrição
		$label = Fabula::GtkLabel("Nome da conta");
		$fixed->put($label, 8, 8);
		$this->widgets['txtDescription'] = Fabula::GtkEntry();
		$this->widgets['txtDescription']->set_size_request(250, 25);
		$fixed->put($this->widgets['txtDescription'], 8, 26);
		
		// Cria o campo servidor
		$label = Fabula::GtkLabel("Servidor");
		$fixed->put($label, 8, 56);
		$this->widgets['txtServer'] = Fabula::GtkEntry();
		$this->widgets['txtServer']->set_size_request(250, 25);
		$fixed->put($this->widgets['txtServer'], 8, 74);
		
		// Cria o campo porta
		$label = Fabula::GtkLabel("Porta");
		$fixed->put($label, 260, 56);
		$this->widgets['txtPort'] = Fabula::GtkEntry();
		$this->widgets['txtPort']->set_size_request(50, 25);
		$fixed->put($this->widgets['txtPort'], 260, 74);
		
		// Cria o campo usuario
		$label = Fabula::GtkLabel("Usuário");
		$fixed->put($label, 8, 104);
		$this->widgets['txtUser'] = Fabula::GtkEntry();
		$this->widgets['txtUser']->set_size_request(250, 25);
		$fixed->put($this->widgets['txtUser'], 8, 122);
		
		// Cria o campo senha
		$label = Fabula::GtkLabel("Senha");
		$fixed->put($label, 8, 152);
		$this->widgets['txtPassword'] = Fabula::GtkEntry();
		$this->widgets['txtPassword']->set_size_request(250, 25);
		$fixed->put($this->widgets['txtPassword'], 8, 170);
		
		// Adiciona os botões
		$this->widgets['btnClose'] = Fabula::GtkButton("Fechar", array($this, "btnClose_onclick"));
		$this->widgets['btnClose']->set_size_request(80, 28);
		$fixed->put($this->widgets['btnClose'], 230, 230);
		
		$this->widgets['btnAction'] = Fabula::GtkButton("Adicionar", array($this, "btnAction_onclick"));
		$this->widgets['btnAction']->set_size_request(80, 28);
		$fixed->put($this->widgets['btnAction'], 140, 230);
		
		// Carrega o treeview
		$this->trvAccounts_onload();
	}
	
	/**
	 * Método que carrega o treeview
	 * 
	 * @name trvAccounts_onload
	 */
	public function trvAccounts_onload() {
		foreach($this->mainObject->config['accounts'] as $account) {
			if(is_array($account)) {
				$this->widgets['trvAccounts']->add_row(array(
					$account['idaccount'],
					$account['description']
				));
			}
		}
		
		$this->widgets['trvAccounts']->add_row(array(0,"Adicionar nova conta"));
	}
	
	/**
	 * Método do botão cancelar
	 * 
	 * @name btnCancel_onclick
	 */
	public function btnClose_onclick() {
		// Cria o arquivo
		$filename = MAIL_PLUGIN_PATH . "config.json";
		
		// Converte para json
		$contents = json_encode($this->mainObject->config);
		
		// Salva o conteudo
		file_put_contents($filename, $contents);
		
		// Carrega os menus novamente
		//$this->mainObject->loadToMenus();
		
		// Fecha a janela
		$this->widgets['frmAddAccounts']->hide();
	}
	
	/**
	 * Método do botão contas
	 * 
	 * @name btnAction_onclick
	 */
	public function btnAction_onclick() {
		// Verifica qual o modo 
		if($this->__idaccount == 0) {
			$data = array();
			$data['idaccount'] = ++$this->mainObject->config['accounts']['counter'];
			$data['description'] = $this->widgets['txtDescription']->get_text();
			$data['server'] = $this->widgets['txtServer']->get_text();
			$data['port'] = $this->widgets['txtPort']->get_text();
			$data['user'] = $this->widgets['txtUser']->get_text();
			$data['password'] = $this->widgets['txtPassword']->get_text();
			$this->mainObject->config['accounts'][] = $data;
			
			// Recarrega a lista de contas
			$this->widgets['trvAccounts']->clear();
			$this->trvAccounts_onload();
		}
		else {
			
			// Busca os dados
			foreach($this->mainObject->config['accounts'] as $key => $account) {
				if($account['idaccount'] == $this->__idaccount) {
					$data = $account;
					break;
				}
			}
			
			$data['description'] = $this->widgets['txtDescription']->get_text();
			$data['server'] = $this->widgets['txtServer']->get_text();
			$data['port'] = $this->widgets['txtPort']->get_text();
			$data['user'] = $this->widgets['txtUser']->get_text();
			$data['password'] = $this->widgets['txtPassword']->get_text();
			$this->mainObject->config['accounts'][$key] = $data;
			
			// Recarrega a lista de contas
			$this->widgets['trvAccounts']->clear();
			$this->trvAccounts_onload();
		}
		
		// Limpa o formulario
		$this->__clearForm();
	}
	
	/**
	 * Método que limpa o formulário
	 * 
	 * @access private
	 * @name __clearForm
	 */
	private function __clearForm() {
		$this->widgets['txtDescription']->set_text("");
		$this->widgets['txtServer']->set_text("");
		$this->widgets['txtPort']->set_text("");
		$this->widgets['txtUser']->set_text("");
		$this->widgets['txtPassword']->set_text("");
	}
	
	/**
	 * Método que adiciona valor ao formulário
	 * 
	 * @access private
	 * @name __setForm
	 * @param array $data Vetor com os dados
	 */
	private function __setForm($data) {
		$this->widgets['txtDescription']->set_text($data['description']);
		$this->widgets['txtServer']->set_text($data['server']);
		$this->widgets['txtPort']->set_text($data['port']);
		$this->widgets['txtUser']->set_text($data['user']);
		$this->widgets['txtPassword']->set_text($data['password']);
	}
	
	/**
	 * Método click do trvAccounts
	 * 
	 * @name trvAccounts_buttonPress
	 */
	public function trvAccounts_buttonPress($widget, $event) {
		// Verifica se é o duplo clique
		if($event->type == Gdk::_2BUTTON_PRESS) {
			// Busca a seleção/model/iter da selecao
			$selection = $widget->get_selection();
			list($model, $iter) = $selection->get_selected();

			// Busca o valor da segunda coluna
			$value = $model->get_value($iter, 0);
			
			// Busca os dados
			foreach($this->mainObject->config['accounts'] as $account) {
				if($account['idaccount'] == $value) {
					$data = $account;
					break;
				}
			}
			
			// Armazena o id
			$this->__idaccount = $value;
			
			// Verifica se é conta nova
			if($this->__idaccount == 0) {
				// Seta os valores
				$this->__clearForm();
				
				// Muda o label do botão
				$this->widgets['btnAction']->set_label("Adicionar");
			}
			else {
				// Seta os valores
				$this->__setForm($data);
				
				// Muda o label do botão
				$this->widgets['btnAction']->set_label("Salvar");
			}
		}
		
	}
}
